<template>
    <div class="warehouse-other-outbound-container">
        <!-- 搜索栏 -->
        <div class="search-bar" style="margin-bottom: 15px;margin-left: 30px;">
            <el-input v-model="searchParams.outboundNo" style="width: 240px; padding-right: 15px;" placeholder="请输入出库单号" />
            <el-input v-model="searchParams.inboundNo" style="width: 240px; padding-right: 15px;" placeholder="请输入其他入库单号" />
            <el-select v-model="searchParams.warehouseId" placeholder="请选择仓库" clearable style="width: 200px; margin-right: 15px;">
                <el-option v-for="warehouse in warehouses" :key="warehouse.id" :label="warehouse.name" :value="warehouse.id" />
            </el-select>
<!--            <el-date-picker v-model="searchParams.startDate" type="date" placeholder="起始日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" style="margin-right: 10px; width: 150px;" />-->
<!--            <el-date-picker v-model="searchParams.endDate" type="date" placeholder="结束日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" style="width: 150px;" />-->
            <el-icon @click="getOtherOutboundList()" style="margin-left: 20px; height: 25px; width: 25px;">
                <Search />
            </el-icon>
            <el-icon style="margin-left: 20px;" @click="resetSearchParams()">
                <Refresh />
            </el-icon>
            <el-button type="success" plain style="margin-left: 30px;" @click="showAddDialog()">创建其他出库单</el-button>
        </div>

        <!-- 其他出库单表格 -->
        <el-table :data="otherOutboundList" style="width: 100%" stripe border="true">
            <el-table-column label="序号" width="80px" #default="scope" align="center">
                {{ scope.$index + 1 }}
            </el-table-column>
            <el-table-column prop="id" label="出库单ID" width="120" align="center" />
            <el-table-column prop="outboundNo" label="出库单号" width="180" align="center" />
            <el-table-column prop="warehouseName" label="仓库名称" width="150" align="center" />
            <el-table-column prop="outboundDate" label="出库日期" width="150" align="center" />
            <el-table-column prop="status" label="出库状态" width="120" #default="scope" align="center">
                <span v-if="scope.row.status == 0" style="color: gray;">草稿</span>
                <span v-if="scope.row.status == 1" style="color: green;">已出库</span>
                <span v-if="scope.row.status == 2" style="color: red;">已取消</span>
            </el-table-column>
            <el-table-column prop="totalAmount" label="总金额" width="120" align="center" />
            <el-table-column prop="remark" label="备注" width="200" align="center" />
            <el-table-column label="操作" width="250px" fixed="right" align="center" #default="scope">
                <el-button type="primary" plain @click="viewOtherOutboundDetails(scope.row.id)">详情</el-button>
                <el-button type="warning" plain @click="showEditDialog(scope.row)">修改</el-button>
                <el-button type="danger" plain @click="handleDeleteOtherOutbound(scope.row.id)">删除</el-button>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div style="position: absolute;bottom: 20px;left: 0;right: 0;height: 25px;width: 300px;margin: 0 auto; ">
            <el-pagination v-model:current-page="pagination.pageNum" v-model:page-size="pagination.pageSize"
                :page-sizes="[3, 5, 10]" layout="total, sizes, prev, pager, next, jumper" :total="pagination.total"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 创建/编辑其他出库单对话框 -->
        <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑其他出库单' : '创建其他出库单'" width="600px"
            :before-close="handleDialogClose" :close-on-click-modal="false">
            <el-form :model="otherOutbound" label-width="120px" style="padding: 15px 0;" :rules="formRules" ref="outboundForm">
                <el-form-item label="出库单号" prop="outboundNo" v-if="isEdit">
                    <el-input v-model="otherOutbound.outboundNo" disabled placeholder="系统自动生成" />
                </el-form-item>
                <el-form-item label="其他入库单号" prop="inboundNo" v-if="!isEdit">
                    <el-select v-model="otherOutbound.inboundNo" placeholder="请选择其他入库单号" clearable @change="handleInboundNoChange">
                        <el-option v-for="inbound in availableInboundList" :key="inbound.id" :label="inbound.inboundNo" :value="inbound.inboundNo" />
                    </el-select>
                </el-form-item>
                <el-form-item label="仓库名称" prop="warehouseId">
                    <el-input v-model="otherOutbound.warehouseName" disabled placeholder="根据其他入库单号自动填充" />
                </el-form-item>
                <el-form-item label="出库日期" prop="outboundDate">
                    <el-date-picker v-model="otherOutbound.outboundDate" type="date" placeholder="请选择出库日期" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="出库状态" prop="status" v-if="isEdit">
                    <el-select v-model="otherOutbound.status" placeholder="请选择出库状态">
                        <el-option label="已出库" :value="1" />
                        <el-option label="已取消" :value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="总金额" prop="totalAmount">
                    <el-input v-model="otherOutbound.totalAmount" type="number" :disabled="!isEdit" placeholder="根据入库单明细自动计算" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="otherOutbound.remark" type="textarea" placeholder="请输入备注信息" />
                </el-form-item>

                <!-- 显示入库单商品明细（只读） -->
                <el-form-item label="入库单明细" v-if="!isEdit && otherOutbound.inboundItems && otherOutbound.inboundItems.length > 0">
                    <el-table :data="otherOutbound.inboundItems" border stripe style="width: 100%">
                        <el-table-column prop="productName" label="商品名称" width="150" />
                        <el-table-column prop="productCode" label="商品编码" width="120" />
                        <el-table-column prop="quantity" label="数量" width="80" align="center" />
                        <el-table-column prop="unitPrice" label="单价" width="100" align="right" />
                        <el-table-column prop="amount" label="金额" width="100" align="right" />
                    </el-table>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDialogClose" size="default">取消</el-button>
                    <el-button type="primary" @click="submitForm" size="default">确认{{ isEdit ? '修改' : '创建' }}</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 其他出库单详情对话框 -->
        <el-dialog v-model="detailDialogVisible" title="其他出库单详情" width="700px" :before-close="handleDetailDialogClose" :close-on-click-modal="false">
            <div v-if="currentOtherOutbound" class="outbound-detail">
                <div class="detail-header">
                    <p><span class="label">出库单号：</span>{{ currentOtherOutbound.outboundNo }}</p>
                    <p><span class="label">其他入库单号：</span>{{ currentOtherOutbound.inboundNo || '无' }}</p>
                    <p><span class="label">仓库名称：</span>{{ currentOtherOutbound.warehouseName }}</p>
                    <p><span class="label">出库日期：</span>{{ currentOtherOutbound.outboundDate }}</p>
                    <p><span class="label">出库状态：</span>
                        <span v-if="currentOtherOutbound.status == 0" style="color: gray;">草稿</span>
                        <span v-if="currentOtherOutbound.status == 1" style="color: green;">已出库</span>
                        <span v-if="currentOtherOutbound.status == 2" style="color: red;">已取消</span>
                    </p>
                    <p><span class="label">总金额：</span>{{ currentOtherOutbound.totalAmount }}</p>
                    <p><span class="label">备注：</span>{{ currentOtherOutbound.remark }}</p>
                </div>

                <div class="detail-items">
                    <h3>出库单明细</h3>
                    <el-table :data="currentOtherOutbound.items" style="width: 100%" stripe border="true">
                        <el-table-column label="序号" width="80px" #default="scope" align="center">
                            {{ scope.$index + 1 }}
                        </el-table-column>
                        <el-table-column prop="productName" label="产品名称" width="180" align="center" />
                        <el-table-column prop="productCode" label="产品编码" width="180" align="center" />
                        <el-table-column prop="quantity" label="数量" width="120" align="center" />
                        <el-table-column prop="unitPrice" label="单价" width="120" align="center" />
                        <el-table-column prop="amount" label="金额" width="120" align="center" />
                    </el-table>
                </div>
            </div>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleDetailDialogClose" size="default">关闭</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted, nextTick } from 'vue';
import { Search, Refresh } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { createOtherOutbound, getOtherOutboundPage, getOtherOutboundWithDetails, updateOtherOutbound, deleteOtherOutbound, getAvailableOtherInboundList, getWarehouseByInboundNo } from '@/api/warehouse/warehouse_other-out';
import { getWarehouseList, getProductList } from '@/api/warehouse/warehouse';

// 获取组件实例用于表单验证
const { proxy } = getCurrentInstance();

// 其他出库单列表数据
const otherOutboundList = ref([]);

// 仓库列表数据（用于选择）
const warehouses = ref([]);

// 产品列表数据（用于选择）
const products = ref([]);

// 可用的其他入库单列表
const availableInboundList = ref([]);

// 搜索参数
const searchParams = ref({
    outboundNo: '',
    inboundNo: '',
    warehouseId: '',
    startDate: '',
    endDate: ''
});

// 分页参数
const pagination = ref({
    pageNum: 1,
    pageSize: 10,
    total: 0
});

// 对话框状态
const dialogVisible = ref(false);
const detailDialogVisible = ref(false);
const isEdit = ref(false);

// 当前操作的其他出库单
const otherOutbound = ref({});
const currentOtherOutbound = ref(null);

// 统一解包工具
function unwrap(res) {
  return (res && res.data !== undefined) ? res.data : res;
}
function unwrapPageRecords(payload) {
  const data = unwrap(payload);
  if (data && Array.isArray(data.records)) {
    return { records: data.records, total: Number(data.total) || data.records.length };
  }
  if (Array.isArray(data)) {
    return { records: data, total: data.length };
  }
  return { records: [], total: 0 };
}

// 表单验证规则
const formRules = ref({
    inboundNo: [
        { required: true, message: '请选择其他入库单号', trigger: 'change' }
    ],
    outboundDate: [
        { required: true, message: '请选择出库日期', trigger: 'change' }
    ],
    totalAmount: [
        { required: true, message: '请输入总金额', trigger: 'blur' }
    ]
});

// 获取其他出库单列表
function getOtherOutboundList() {
    // 构建分页参数
    const pageParams = {
        pageNum: pagination.value.pageNum,
        pageSize: pagination.value.pageSize,
        outboundNo: searchParams.value.outboundNo,
        inboundNo: searchParams.value.inboundNo,
        warehouseId: searchParams.value.warehouseId,
        startDate: searchParams.value.startDate,
        endDate: searchParams.value.endDate
    };

    getOtherOutboundPage(pageParams).then(res => {
        const page = unwrapPageRecords(res);
        otherOutboundList.value = page.records;
        pagination.value.total = page.total;
    }).catch(error => {
        ElMessage.error('获取其他出库单列表失败');
        console.error('获取其他出库单列表失败:', error);
    });
}

// 获取仓库列表（用于选择）
function fetchWarehouses() {
    getWarehouseList().then(res => {
        const data = unwrap(res);
        warehouses.value = Array.isArray(data) ? data : (Array.isArray(data?.records) ? data.records : []);
    }).catch(error => {
        ElMessage.error('获取仓库列表失败');
        console.error('获取仓库列表失败:', error);
    });
}

// 获取产品列表（用于选择）
function fetchProducts() {
    getProductList().then(res => {
        const data = unwrap(res);
        products.value = Array.isArray(data) ? data : (Array.isArray(data?.records) ? data.records : []);
    }).catch(error => {
        ElMessage.error('获取产品列表失败');
        console.error('获取产品列表失败:', error);
    });
}

// 获取可用的其他入库单列表
function fetchAvailableInboundList() {
    getAvailableOtherInboundList().then(res => {
        const data = unwrap(res);
        availableInboundList.value = Array.isArray(data) ? data : [];
    }).catch(error => {
        ElMessage.error('获取可用其他入库单列表失败');
        console.error('获取可用其他入库单列表失败:', error);
    });
}

// 根据其他入库单号获取仓库信息
function handleInboundNoChange(inboundNo) {
    if (inboundNo) {
        getWarehouseByInboundNo(inboundNo).then(res => {
            const data = unwrap(res);
            if (data && data.warehouseId) {
                otherOutbound.value.warehouseId = data.warehouseId;
                otherOutbound.value.warehouseName = data.warehouseName;

                // 自动填充总金额（从入库单明细计算得出）
                if (data.totalAmount) {
                    otherOutbound.value.totalAmount = data.totalAmount;
                }

                // 保存商品明细信息（用于后续处理）
                otherOutbound.value.inboundItems = data.items || [];
            }
        }).catch(error => {
            ElMessage.error('获取仓库信息失败');
            console.error('获取仓库信息失败:', error);
        });
    } else {
        otherOutbound.value.warehouseId = '';
        otherOutbound.value.warehouseName = '';
        otherOutbound.value.totalAmount = null;
        otherOutbound.value.inboundItems = [];
    }
}

// 重置搜索参数
function resetSearchParams() {
    searchParams.value = {
        outboundNo: '',
        inboundNo: '',
        warehouseId: '',
        startDate: '',
        endDate: ''
    };
    getOtherOutboundList();
}

// 分页处理
const handleSizeChange = (val) => {
    pagination.value.pageSize = val;
    getOtherOutboundList();
}
const handleCurrentChange = (val) => {
    pagination.value.pageNum = val;
    getOtherOutboundList();
}

// 显示创建对话框
function showAddDialog() {
    isEdit.value = false;
    otherOutbound.value = {
        inboundItems: [] // 初始化入库单明细字段
    };
    dialogVisible.value = true;
    // 重置表单
    nextTick(() => {
        proxy.$refs.outboundForm.resetFields();
    });
    // 获取可用的其他入库单列表
    fetchAvailableInboundList();
}

// 显示编辑对话框
function showEditDialog(row) {
    isEdit.value = true;
    otherOutbound.value = { ...row };
    dialogVisible.value = true;
}

// 关闭对话框
function handleDialogClose() {
    dialogVisible.value = false;
    // 重置表单
    proxy.$refs.outboundForm.resetFields();
}

// 提交表单
function submitForm() {
    proxy.$refs.outboundForm.validate((valid) => {
        if (valid) {
            if (isEdit.value) {
                // 更新其他出库单
                updateOtherOutbound(otherOutbound.value).then(res => {
                    ElMessage.success('其他出库单更新成功');
                    handleDialogClose();
                    getOtherOutboundList();
                }).catch(error => {
                    ElMessage.error('其他出库单更新失败');
                    console.error('更新失败:', error);
                });
            } else {
                // 创建其他出库单
                const outboundData = {
                    ...otherOutbound.value,
                    warehouseId: otherOutbound.value.warehouseId,
                    inboundNo: otherOutbound.value.inboundNo, // 保存入库单号关联
                    inboundItems: otherOutbound.value.inboundItems // 传递入库单明细，用于创建出库单明细
                };

                // 创建出库单（包含明细）
                createOtherOutbound(outboundData).then(res => {
                    const createdOutbound = unwrap(res);
                    if (createdOutbound && createdOutbound.id) {
                        ElMessage.success('其他出库单创建成功');
                        handleDialogClose();
                        getOtherOutboundList();
                    }
                }).catch(error => {
                    ElMessage.error('其他出库单创建失败');
                    console.error('创建失败:', error);
                });
            }
        } else {
            ElMessage.warning('请完善其他出库单信息并确保格式正确');
            return false;
        }
    });
}

// 查看其他出库单详情
function viewOtherOutboundDetails(id) {
    getOtherOutboundWithDetails(id).then(res => {
        const data = unwrap(res);
        currentOtherOutbound.value = data || null;
        detailDialogVisible.value = true;
    }).catch(error => {
        ElMessage.error('获取其他出库单详情失败');
        console.error('获取详情失败:', error);
    });
}

// 关闭详情对话框
function handleDetailDialogClose() {
    detailDialogVisible.value = false;
    currentOtherOutbound.value = null;
}

// 删除其他出库单
function handleDeleteOtherOutbound(id) {
    ElMessageBox.confirm(
        '确定要删除该其他出库单吗？此操作不可撤销。',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        deleteOtherOutbound(id).then(res => {
            ElMessage.success('其他出库单删除成功');
            getOtherOutboundList();
        }).catch(error => {
            ElMessage.error('其他出库单删除失败');
            console.error('删除失败:', error);
        });
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
}

// 页面加载时获取其他出库单列表、仓库列表和产品列表
onMounted(() => {
    getOtherOutboundList();
    fetchWarehouses();
    fetchProducts();
});
</script>

<style scoped>
.warehouse-other-outbound-container {
    padding: 20px;
}

.search-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.outbound-detail {
    padding: 10px;
}

.detail-header {
    margin-bottom: 20px;
}

.detail-header p {
    margin: 8px 0;
}

.label {
    font-weight: bold;
    display: inline-block;
    width: 100px;
}

.detail-items h3 {
    margin-bottom: 10px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>
